import os
import random
import tempfile
import uuid
from io import BytesIO

from flask import Flask, render_template, request, jsonify, send_file
from pdf2image import convert_from_path

from enums.express_brand_enum import ExpressBrand
from rsp.express_brand_rsp import ExpressBrandRsp
from pdf import LabelGenerator

app = Flask(__name__)

if __name__ == '__main__':
    app.run(debug=True)


@app.route('/electronic')
def index():
    return render_template('index.html')


@app.route('/electronic/generate_brands')
def generate_brands():
    brands = [ExpressBrandRsp(brand.code, brand.desc).to_dict() for brand in ExpressBrand]
    return jsonify(brands)


@app.route('/electronic/generate', methods=['POST'])
def generate_label():
    brand = request.json.get('brand')
    brand_enum = ExpressBrand.from_code(brand)

    label_image = generate_label_image(brand_enum)

    # 返回生成的电子面单图像
    return jsonify({'label_url': label_image})


def read_file(brand):
    with open('./static/waybill/' + brand.lower() + '.txt', 'r', encoding='utf-8') as file:
        content = file.read()
        return content


def generate_label_image(brand_enum):
    temp_dir = tempfile.gettempdir()
    random_uuid = str(uuid.uuid4()) + ".pdf"

    barcode_data = get_random_line(brand_enum.code)

    pdf_path = temp_dir + os.sep + random_uuid

    LabelGenerator.generate_label_image(brand_enum, pdf_path, barcode_data)
    img_data = pdf_to_image(pdf_path)
    # 使用 send_file 返回图像，并确保返回 URL 而不是直接返回文件
    image_response = send_file(
        BytesIO(img_data),
        mimetype='image/png',
        as_attachment=False,
        download_name='label.png'  # 更新参数名
    )

    import base64
    img_base64 = base64.b64encode(img_data).decode('utf-8')
    return f'data:image/png;base64,{img_base64}'


def get_random_line(brand):
    # 打开文件并读取所有行
    with open('./static/waybill/' + brand.lower() + '.txt', 'r', encoding='utf-8') as file:
        lines = file.readlines()

    # 去除每行末尾的换行符
    lines = [line.strip() for line in lines]

    # 随机选择一行
    if lines:
        random_line = random.choice(lines)
        return random_line
    else:
        return None


def pdf_to_image(pdf_path):
    images = convert_from_path(pdf_path)
    img_byte_arr = BytesIO()
    images[0].save(img_byte_arr, format='PNG')
    img_byte_arr = img_byte_arr.getvalue()
    return img_byte_arr
